<?php


namespace App\Service\Store;

use App\Constants\Integral;
use App\Dao\IntegralDetailDao;
use App\Dao\UserDao;
use Hyperf\Di\Annotation\Inject;

/**
 * 积分服务
 * @author 陈奕文
 * Class IntegralService
 * @package App\Service\Store
 */
class IntegralService
{

    /**
     * 积分详情
     * @Inject()
     * @var IntegralDetailDao
     */
    public $dao;

    /**
     * 用户
     * @Inject()
     * @var UserDao
     */
    public $user_dao;

    /**
     * 返回积分列表
     * @param array $params
     * @return array
     */
    public function getIntegralList(array $params)
    {
        $map = [];
        isset($params['start_time']) && !isset($params['end_time']) && $map['created_at'] = ['>=', strtotime($params['start_time'])]; // 注册开始时间
        isset($params['end_time']) &&  !isset($params['start_time']) && $map['created_at'] = ['<=', strtotime($params['end_time'])]; // 注册结束时间
        isset($params['end_time']) &&  isset($params['start_time']) && $map['between_field'] = ['created_at' =>[strtotime($params['start_time']), strtotime($params['end_time'])]]; // 有创建开始和结束时间

        isset($params['phone']) && $map['phone'] = ['like',"%{$params['name']}%"]; // 账号

        isset($params['search']) && $map['name'] = ['like',"%{$params['search']}%"]; // 搜索用户名 /姓名

        $sort = 'created_at desc'; // 排序
        $select = ['id', 'created_at', 'name', 'phone', 'integral'];
        // 分页
        $page_size = null;
        isset($params['page']) && $page_size = isset($params['page_size'])? $params['page_size']: 20;

        // 获取符合条件的用户
        $user_list = $this->user_dao->getUsersByMap($map, $sort, $select, $page_size)->toArray();
        // 拼接
        if (isset($user_list['data'])) {
            $user_list['data'] = $this->joinIntegralData($user_list['data']);
        } else {
            $user_list = $this->joinIntegralData($user_list);
        }

        return $user_list;
    }

    /**
     * 拼接积分数据
     * @param array $user_list
     * @return array
     */
    public function joinIntegralData(array $user_list)
    {
        $ids = array_column($user_list, 'id');

        $selectRaw = "user_id, SUM(CASE WHEN status=1 AND type=1 THEN num END) as consume_income"; // 消费收入
        $selectRaw .= ",SUM(CASE WHEN status=2 AND type=1 THEN num END) as share_income"; // 分享收入
        $selectRaw .= ",SUM(CASE WHEN status=(3 OR 4 OR 5) AND type=1 THEN num END) as other_income"; // 其他收入
        $selectRaw .= ",SUM(CASE WHEN type=1 THEN num END) as consume"; // 支出积分
        $group_by = 'user_id';
        $consume_incomes = $this->dao->getIntegralCountByUserIds($ids, $selectRaw, $group_by)->pluck('consume_income','user_id')->toArray(); // 消费收入
        $share_incomes = $this->dao->getIntegralCountByUserIds($ids, $selectRaw, $group_by)->pluck('share_income','user_id')->toArray(); // 分享收入
        $other_incomes = $this->dao->getIntegralCountByUserIds($ids, $selectRaw, $group_by)->pluck('other_income','user_id')->toArray(); // 其他收入
        $consumes = $this->dao->getIntegralCountByUserIds($ids, $selectRaw, $group_by)->pluck('consume','user_id')->toArray(); // 支出积分

        foreach ($user_list as $key => $item) {
            $user_list[$key]['consume_income'] = [ // 消费收入
                'status' => [1],
                'type' => 1,
                'number' => 0
            ];
            $user_list[$key]['share_income'] = [ // 分享收入
                'status' => [2],
                'type' => 1,
                'number' => 0
            ];
            $user_list[$key]['other_income'] = [ // 其他收入
                'status' => [3, 4, 5],
                'type' => 1,
                'number' => 0
            ];
            $user_list[$key]['consume'] = [ // 支出积分
                'type' => 2,
                'number' => 0
            ];
            $user_list[$key]['create_time'] = date('Y-m-d H:i:s', $item['created_at']); // 注册时间
            isset($consume_incomes[$item['id']]) &&  $user_list[$key]['consume_income']['number'] = $consume_incomes[$item['id']];// 消费收入
            isset($share_incomes[$item['id']]) &&  $user_list[$key]['share_income']['number'] = $share_incomes[$item['id']]; // 分享收入
            isset($other_incomes[$item['id']]) &&  $user_list[$key]['other_income']['number'] = $other_incomes[$item['id']]; // 其他收入
            isset($consumes[$item['id']]) &&  $user_list[$key]['consume']['number'] = $consumes[$item['id']]; // 支出积分

        }
        return $user_list;
    }

    /**
     * 获取积分详情
     * @param array $params
     * @return array
     */
    public function getDetails(array $params)
    {
        $map = [];
        isset($params['user_id']) && $map['user_id'] = (int)$params['user_id']; // 用户ID

        if (isset($params['status'])) {// 积分状态
            if (is_array($params['status'])) {
                $map['status'] = ['in', $params['status']];
            } else {
                $map['status'] = (int)$params['status'];
            }
        }

        isset($params['type']) && $map['type'] = (int)$params['type']; // 积分类型
        $sort = 'id desc';
        // 分页
        $page_size = null;
        isset($params['page']) && $page_size = isset($params['page_size'])? $params['page_size']: 20;
        // 获得符合条件的积分详情
        $integral_list = $this->dao->getIntegralDetailsMap($map, $sort, null, $page_size)->toArray();
        // 拼接
        if (isset($integral_list['data'])) {
            $integral_list['data'] = $this->joinUserData($integral_list['data']);
        } else {
            $integral_list = $this->joinUserData($integral_list);
        }

        return $integral_list;
    }

    /**
     * 拼接用户数据
     * @param array $integral_list
     * @return array
     */
    public function joinUserData(array $integral_list)
    {
        $user_ids = array_column($integral_list, 'user_id'); // 用户ID
        $lower_ids = array_column($integral_list, 'lower_id'); // 所有关联的下级用户ID
        $total_ids = array_merge($user_ids, $lower_ids);
        $total_ids = array_unique(array_filter($total_ids)); // 用户ID和下级用户ID集合
        $select = ['id', 'name'];
        // 查出用户ID集合对应的用户名
        $names = $this->user_dao->getUsersByIdsNotGroup($total_ids, $select)->pluck('name', 'id')->toArray();

        foreach ($integral_list as $key => $item) {
            $integral_list[$key]['status_text'] = Integral::STATUS_LIST[$item['status']] ?? ""; // 积分状态
            $integral_list[$key]['type_text'] = Integral::TYPE_LIST[$item['type']] ?? ""; // 积分收入
            $integral_list[$key]['lower_name'] = $names[$item['lower_id']] ?? ""; // 下级用户名称
            $integral_list[$key]['user_name'] = $names[$item['user_id']] ?? ""; // 当前用户名称
            $integral_list[$key]['create_time'] = date('Y-m-d H:i:s', (int)$item['create_time']); // 注册时间

        }

        return $integral_list;
    }



}